<template>
  <span ref="textElement" class="editable" @dblclick="enterEditMode">{{ props.text }}</span>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'

const props = defineProps({
  text: {
    type: String,
    required: true
  }
})

watch(
  () => props.text,
  (newText) => {
    if (textElement.value) {
      textElement.value.innerText = newText
    }
  }
)

const emit = defineEmits(['edited', 'update:text', 'startEdit'])

const textElement = ref<any>(null)
const enterEditMode = (e): void => {
  emit('startEdit')
  if (!textElement.value) return
  textElement.value.contentEditable = true // 开启可编辑
  textElement.value.focus() // 聚焦元素
  selectAllText(textElement.value) // 全选文字

  // 3. 监听回车和失焦事件保存
  textElement.value.addEventListener('keydown', handleKeyDown)
  textElement.value.addEventListener('blur', exitEditMode)
}

// 4. 退出编辑模式
const exitEditMode = (): void => {
  textElement.value.contentEditable = false // 关闭可编辑

  // 移除事件监听
  textElement.value.removeEventListener('keydown', handleKeyDown)
  textElement.value.removeEventListener('blur', exitEditMode)

  const updateText = textElement.value.innerText
  textElement.value.innerText = props.text
  //更新数据
  emit('edited', updateText)
  emit('update:text', updateText)
}

// 5. 处理回车键（保存并退出）
const handleKeyDown = (e: KeyboardEvent): void => {
  if (e.key === 'Enter') {
    e.preventDefault() // 阻止换行
    textElement.value.removeEventListener('blur', exitEditMode)
    exitEditMode()
  }
}

// 6. 全选文字功能
const selectAllText = (element: any): void => {
  const range = document.createRange()
  range.selectNodeContents(element)

  const selection = window.getSelection()
  if (selection) {
    selection.removeAllRanges()
    selection.addRange(range)
  }
}
</script>

<style scoped lang="scss">
.editable {
  cursor: text;
}
.editable:focus {
  border-bottom: 1px solid $delta-color-lan; /* 编辑时的蓝色边框 */
  background: #f5f5f5; /* 编辑时的背景色 */
}
</style>
